import { ref, watch } from 'vue'
import imageCacheService from '@/utils/imageCache'

/**
 * 图片缓存组合式函数
 */
export function useImageCache() {
  const cachedUrl = ref<string>('')
  const loading = ref<boolean>(false)
  const error = ref<string>('')

  /**
   * 缓存图片
   */
  const cacheImage = async (originalUrl: string) => {
    if (!originalUrl) {
      cachedUrl.value = ''
      return
    }

    loading.value = true
    error.value = ''

    try {
      const url = await imageCacheService.getImageUrl(originalUrl)
      cachedUrl.value = url
    } catch (err) {
      error.value = err instanceof Error ? err.message : '缓存失败'
      cachedUrl.value = originalUrl // 失败时使用原始URL
    } finally {
      loading.value = false
    }
  }

  /**
   * 监听URL变化并自动缓存
   */
  const watchUrl = (url: string) => {
    watch(
      () => url,
      (newUrl) => {
        cacheImage(newUrl)
      },
      { immediate: true }
    )
  }

  return {
    cachedUrl,
    loading,
    error,
    cacheImage,
    watchUrl
  }
}

export default useImageCache
